<template>
  <div class="app-container">
    <div v-show="!assetDetailInfo.visible">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query"
          :filter-list="filterInfo.list"
          :filter-btn="filterInfo.btn"
        >
          <template v-slot:filter-monthName>
            <el-input
              v-model="filterInfo.query.monthNameMult"
              class="not-mongolia"
              type="input"
              :required="true"
              :disabled="true"
              :placeholder="'请选择会计期间'"
              style="width: 100%"
            >
              <template #append>
                <el-icon @click="checkFiscalPeriodStart()"
                  ><MoreFilled
                /></el-icon>
              </template>
            </el-input>
          </template>
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList"> </NewPageFilter>
      </div>
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :checkBox="false"
        :field-list="tableInfo.fieldList"
        :spanMethod="spanMethod"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-assetCode="scope">
          <span
            v-if="scope.row.assetCode"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.assetCode }}</span
          >
          <span v-else>-</span>
        </template>
      </TableContainer>
    </div>

    <assetCard-detail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      @returnBack="getList"
    />
    <PageDialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio label="page">当前页数据</el-radio>
          <el-radio label="all">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </PageDialog>
    <SelectFiscalPeriod
      v-if="selectFiscalPeriodInfo.visible"
      v-model:show-dialog="selectFiscalPeriodInfo.visible"
      :api="getBaseFiscalPeriodPage"
      :save-empty="true"
      :check-box="true"
      :highlight-row="false"
      :query="selectFiscalPeriodInfo.query"
      @callback="callBackSelectFiscalPeriod"
    />
  </div>
</template>

<script setup name="costStructureAnalysis">
import {
  getAssetCostStructureAnalysis,
  excelAssetCostStructureAnalysis,
} from '@/api/dataQuery.js'
import { getBaseFiscalPeriodPage } from '@/api/base'
import AssetCardDetail from '@/views/asset/assetManage/assetCard/details'
import { getDeptAll, getCurrentFiscalPeriod } from '@/api/core'
const { proxy } = getCurrentInstance()
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: 'page',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '导出',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    sort: 'create_time desc',
    // deptAuth: 'id',
    // supplierAuth: 'supplierId',
    // depotAuth: 'id',
  },
  copyQuery: {},
  list: [
    {
      slot: 'true',
      label: '月份',
      value: 'monthName',
      event: search,
    },

    {
      componentType: 'input',
      label: '资产卡片号',
      value: 'assetCode',
      event: search,
    },
    {
      componentType: 'input',
      label: '资产名称',
      value: 'assetName',
      event: search,
    },
    {
      componentType: 'input',
      label: '规格',
      value: 'standard',
      event: search,
    },
    {
      componentType: 'input',
      label: '厂家名称',
      value: 'brandName',
      event: search,
    },
    {
      label: '使用部门',
      value: 'useDeptIdMult',
      query: {
        // deptAuth: 'id',
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      multiple: true,
      event: search,
    },
    {
      label: '管理部门',
      value: 'manageDeptIdMult',
      query: {
        // deptAuth: 'id',
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      multiple: true,
      event: search,
    },
  ],
  btn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('costStructureAnalysis:exportExcel'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: null,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'slot',
    },
    {
      label: '资产名称',
      type: 'multiHeader',
      value: 'assetName',
    },
    { label: '规格', value: 'standard' },
    { label: '厂家', value: 'brandName' },
    { label: '使用部门', value: 'useDeptName' },
    { label: '管理部门', value: 'manageDeptName' },
    {
      label: '月份',
      value: 'monthName',
    },
    {
      label: '总成本',
      value: 'allCostAmount',
    },
    {
      label: '固定成本',
      value: 'fixeCost',
      type: 'multiHeader',
      children: [
        {
          label: '设备折旧成本',
          value: 'depreciationAmount',
          width: '120px',
        },
        {
          label: '房屋折旧成本',
          value: 'houseDepreciationAmount',
          width: '120px',
        },
        {
          label: '人工成本',
          value: 'labourAmount',
        },
      ],
    },
    {
      label: '变动成本',
      value: 'variableCost',
      type: 'multiHeader',
      children: [
        {
          label: '维修成本',
          value: 'repairAmount',
        },
        {
          label: '养护成本',
          value: 'maintenanceAmount',
        },
        {
          label: '耗材成本',
          value: 'materialAmount',
        },
        {
          label: '药品成本',
          value: 'drugAmount',
        },
        {
          label: '水电成本',
          value: 'utilitiesAmount',
        },
        /* {
          label: '自定义成本1',
          value: 'customAmount1',
        },
        {
          label: '自定义成本2',
          value: 'customAmount2',
        },
        {
          label: '其他成本',
          value: 'otherAmount',
        }, */
      ],
    },
  ],
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
})
const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const selectFiscalPeriodInfo = ref({
  visible: false,
  query: {
    fiscalType: 2,
  },
})
watch(
  () => tableInfo.value.data,
  (val) => {
    val.forEach((element, index) => {
      const otherCostMap = element.otherCostMap
      for (const key in otherCostMap) {
        if (Object.hasOwnProperty.call(otherCostMap, key)) {
          const ele = otherCostMap[key]
          tableInfo.value.data[index][key] = ele
        }
      }
    })
  }
)
onMounted(() => {
  getCurrentFiscalPeriod(2).then(res => {
    if(res && res.success){
      filterInfo.value.query.monthNameMult = res.data.name
      filterInfo.value.copyQuery = proxy.$fn.deepClone(filterInfo.value.query)
      getList()
      addDictColumn()
    }
  })
})
function checkFiscalPeriodStart() {
  selectFiscalPeriodInfo.value.visible = true
}
function callBackSelectFiscalPeriod(data) {
  if (data && data.length) {
    filterInfo.value.query.monthNameMult = data
      .map((item) => item.name)
      .toString()
    search()
  } else {
    filterInfo.value.query.monthNameMult = ''
    search()
  }
}
// 添加动态字典配置列
function addDictColumn() {
  let asset_cost_project =
    proxy.$store.state.permission.dict['asset_cost_project']
  if (asset_cost_project && asset_cost_project.length) {
    let fieldList = []
    asset_cost_project.map((item) => {
      if (item.isEnable === 1 && item.dictType === 1) {
        let obj = {
          label: item.name,
          value: item.code,
        }
        fieldList.push(obj)
      }
    })
    tableInfo.value.fieldList.forEach((element, index) => {
      if (element.value === 'variableCost') {
        tableInfo.value.fieldList[index].children =
          element.children.concat(fieldList)
      }
    })
  }
}
function handleClose() {
  dialogInfo.value.visible = false
}
function checkConfirm() {
  exportExcelList()
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function exportExcel() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
  dialogInfo.value.flag = 'page'
}
function exportExcelList() {
  filterInfo.value.query.idMult = ''
  if (dialogInfo.value.flag === 'select') {
    if (!tableInfo.value.selections.length) {
      Message.warning({
        message: '请选择数据！',
        showClose: true,
        duration: 3000,
      })
      return
    }
    let ids = tableInfo.value.selections.map((item) => item.id).join(',')
    filterInfo.value.query.idMult = ids
  }
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: dialogInfo.value.flag === 'page' ? true : false,
  }
  excelAssetCostStructureAnalysis(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
// 获取列表
function getList() {
  if(!filterInfo.value.query.monthNameMult){
    proxy.$message({
      message: `请选择会计期间`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  tableInfo.value.api = getAssetCostStructureAnalysis
  tableInfo.value.refresh = Math.random()
}
function clearSearch() {
  filterInfo.value.query = proxy.$fn.deepClone(filterInfo.value.copyQuery)
  search()
}
// 搜索
function search() {
  // 重置分页
  if(!filterInfo.value.query.monthNameMult){
    proxy.$message({
      message: `请选择会计期间`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  tableInfo.value.api = getAssetCostStructureAnalysis
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}

function spanMethod({ row, column, rowIndex, columnIndex }) {
  let keys = [
    'assetCode',
    'assetName',
    'standard',
    'brandName',
    'useDeptName',
    'manageDeptName',
  ]
  // 注意:字段列表要按表格排列的顺序排列,如果后续字段不再需要进行行合并,可以省略后面的字段,如果中间某字段要跳过合并,要用空字符串顶位
  return proxy.$fn.spanMethod(tableInfo.value.data, keys, rowIndex, columnIndex)
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}

//跳转资产卡片详情
function showDetail(row) {
  if (row.assetId && row.assetId !== -2) {
    assetDetailInfo.value.id = row.assetId
    assetDetailInfo.value.visible = true
  }
}
</script>
<style scoped></style>
